#!/usr/bin/env sh

set -e

build() {
    repo=${BASE_REPO:-"registry.cn-shenzhen.aliyuncs.com/wena"}
    fn="$1"

    if [ -z "${fn}" ]; then
        echo "build.sh <dockerfile path>"
        return 1
    fi

    if [ ! -s "${fn}" ]; then
        echo "${fn} not exist or is empty"
        return 1
    fi

    push=$2

    hn="$(cat $fn | head -n 1)"
    name="$(echo ${hn} | awk '{print $2}')"
    bn="$(echo ${hn} | awk '{print $3}')"
    vern="$(echo ${hn} | awk '{print $4}')"
    vers=(${vern//./ })

    unset ver
    tags="${repo}/${name}:${bn}"
    for c in ${vers[@]}; do
        if [ -n "${ver}" ]; then
            ver="${ver}.${c}"
        else
            ver="${c}"
        fi

        tags="${tags} ${repo}/${name}:${bn}-${ver}"
    done

    unset buildTags
    for tag in $(echo ${tags}); do
        buildTags="--tag ${tag} ${buildTags}"
    done

    buildScript="docker build --file ${fn} ${buildTags} --label ${name}.name=${bn} --label ${name}.version=${vern} --build-arg repo=${repo} ."
    echo ${buildScript}
    eval ${buildScript}

    if [ "${push}" == "push" ]; then
        for tag in $(echo ${tags}); do
            pushScript="docker push --quiet ${tag}"
            echo ${pushScript}
            eval ${pushScript}
        done
    fi
}

build $@
